package com.example.text.service.impl;


import com.example.text.entity.News;
import com.example.text.repository.NewsRepository;
import com.example.text.service.NewsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class NewsServiceImpl implements NewsService {
    private final NewsRepository newsRepository;

    @Override
    public News save(News news) {
        log.info("保存资讯: {}", news.getTitle());
        return newsRepository.save(news);
    }

    @Override
    public Optional<News> findById(String id) {
        log.info("根据ID查询资讯: {}", id);
        return newsRepository.findById(id);
    }

    @Override
    public void deleteById(String id) {
        log.info("删除资讯: {}", id);
        if (newsRepository.existsById(id)) {
            newsRepository.deleteById(id);
        } else {
            throw new RuntimeException("文档不存在，ID: " + id);
        }
    }

    @Override
    public List<News> findAll() {
        log.info("查询所有资讯");
        return (List<News>) newsRepository.findAll();
    }

    @Override
    public SearchHits<News> search(String keyword) {
        log.info("搜索资讯，关键字: {}", keyword);
        return newsRepository.findByKeyword(keyword);
    }

    @Override
    public List<News> searchWithoutHighlight(String keyword) {
        log.info("搜索资讯(无高亮)，关键字: {}", keyword);
        if (keyword == null || keyword.trim().isEmpty()) {
            return findAll();
        }
        return newsRepository.findByTitleContainingOrContentContaining(keyword, keyword);
    }
}
